from tornado.web import RequestHandler
from settings.config import config
from custom.utils import json_result


class BaseRequestHandler(RequestHandler):
    """
    base handler
    """
    @property
    def json_encoder(self):
        return self.application.json_encoder

    @property
    def weibo_spider(self):
        return self.application.wb_spider

    @property
    def db(self):
        return self.application.db

    def redirect404(self):
        self.redirect(config.default_404_url)

    def prepare(self):
        return super(BaseRequestHandler, self).prepare()

    def get(self, *args, **kwargs):
        super(BaseRequestHandler, self).get(*args, **kwargs)

    """
    def write_error(self, status_code, **kwargs):
        super()
    """

    def success(self, code=200, msg='', data=None):
        """
        成功返回
        :param data: 
        :param code: 
        :param msg: 
        :return: 
        """
        self.write(json_result(code, msg, data))
        self.finish()

    def error(self, code=-1, msg='', data=None):
        """
        失败返回
        :param data: 
        :param code: 
        :param msg: 
        :return: 
        """
        self.write(json_result(code, msg, data))
        self.finish()
